package com.example.administrator.trains;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TicketFragment extends Fragment {
    Button btn_search;
    ImageButton ibtn_add;
    ImageButton ibtn_flash;
    ImageButton ibtn_dowmload;
    private byte one_data;
    private int k = 0;
    List<Map<String,String>> list2 = new ArrayList<Map<String, String>>();
    List<Map<String,String>> list3 = new ArrayList<Map<String, String>>();
    List<Map<String,String>> list = new ArrayList<Map<String, String>>();
    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                ListView lv = (ListView)getActivity().findViewById(R.id.ticket_lv);
                ListAdapter la = new SimpleAdapter(getActivity(), list2,
                        R.layout.activity_show_list_item,
                        new String[]{"type1", "type2", "type3", "type4",
                                "vehicleNum", "startPlace", "endPlace",
                                "startTime", "endTime", "type", "show_type1_num",
                                "show_type2_num", "show_type3_num", "show_type4_num",
                                "show_type1_price", "show_type2_price", "show_type3_price",
                                "show_type4_price"},
                        new int[]{R.id.type1, R.id.type2, R.id.type3, R.id.type4, R.id.vehicleNum,
                                R.id.startPlace, R.id.endPlace,
                                R.id.information, R.id.endTime,
                                R.id.type, R.id.num1, R.id.num2,
                                R.id.num3, R.id.num4, R.id.price1,
                                R.id.price2, R.id.price3, R.id.price4});
                lv.setAdapter(la);

                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent i = new Intent(getActivity(),admin_change_ticket.class);

                        i.putExtra("type1",list2.get(position).get("type1").toString());
                        i.putExtra("type2",list2.get(position).get("type2").toString());
                        i.putExtra("type3",list2.get(position).get("type3").toString());
                        i.putExtra("type4",list2.get(position).get("type4").toString());
                        i.putExtra("date",list2.get(position).get("date").toString());
                        i.putExtra("startPlace",list2.get(position).get("startPlace").toString());
                        i.putExtra("endPlace",list2.get(position).get("endPlace").toString());
                        i.putExtra("startTime",list2.get(position).get("startTime").toString());
                        i.putExtra("endTime",list2.get(position).get("endTime").toString());
                        i.putExtra("orderNum",list2.get(position).get("vehicleNum").toString());
                        i.putExtra("price1",list2.get(position).get("type1_price").toString());
                        i.putExtra("price2",list2.get(position).get("type2_price").toString());
                        i.putExtra("price3",list2.get(position).get("type3_price").toString());
                        i.putExtra("price4",list2.get(position).get("type4_price").toString());
                        i.putExtra("train_type",list2.get(position).get("type").toString());
                        i.putExtra("num1",list2.get(position).get("type1_num").toString());
                        i.putExtra("num2",list2.get(position).get("type2_num").toString());
                        i.putExtra("num3",list2.get(position).get("type3_num").toString());
                        i.putExtra("num4",list2.get(position).get("type4_num").toString());

                        startActivity(i);
                    }
                });}
            if(msg.what==2){
                Toast.makeText(getActivity(),"车次格式不符合要求",Toast.LENGTH_LONG).show();
            }
        }
    };

    private void recv_ticket_msg(){
        Thread newThread; //声明一个子线程
        try {
            Socket.connector.send(Socket.connector.package_data(Socket.connector.TICKET_CMD_TYPE,
                    Socket.connector.ALL_ORDER, "00", "00"));
            Socket.connector.recv_ack();
            if (CommunicationData.ack == "01") {
                newThread = new Thread(new Runnable(){
                    @Override
                    public void run() {
                        list2.clear();
                        byte[] buffer = new byte[20000];
                        int j = 1;
                        byte[] one_ticket = new byte[30];
                        byte[] from_station = new byte[30];
                        byte[] to_station = new byte[30];
                        byte[] train_number = new byte[10];
                        byte[] departure_time = new byte[10];
                        byte[] arrival_time = new byte[10];
                        byte[] type1_price = new byte[5];
                        byte[] type2_price = new byte[5];
                        byte[] type3_price = new byte[5];
                        byte[] type4_price = new byte[5];
                        byte[] to_date = new byte[11];
                        byte[] type1_num = new byte[5];
                        byte[] type2_num = new byte[5];
                        byte[] type3_num = new byte[5];
                        byte[] type4_num = new byte[5];
                        byte[] train_type = new byte[4];

                        try {
                            //接收对应车次的当天的车票
                            Socket.connector.rec_data(buffer);
                            Socket.connector.send(Socket.connector.hexStringToByteArray(Socket.connector.ACK_OK));
                        } catch (IOException e) {
                        }

                        for (int i = 7; i > 0; i++) {
                            one_data = buffer[i];
                            if (one_data == '|') {
                                switch (j) {
                                    case 1:
                                        from_station = one_ticket.clone();
                                        break;
                                    case 2:
                                        to_station = one_ticket.clone();
                                        break;
                                    case 3:
                                        departure_time = one_ticket.clone();
                                        break;
                                    case 4:
                                        arrival_time = one_ticket.clone();
                                        break;
                                    case 5:
                                        train_number = one_ticket.clone();
                                        train_type[0] = train_number[0];
                                        break;
                                    case 6:
                                        type1_price = one_ticket.clone();
                                        break;
                                    case 7:
                                        type2_price = one_ticket.clone();
                                        break;
                                    case 8:
                                        type3_price = one_ticket.clone();
                                        break;
                                    case 9:
                                        type4_price = one_ticket.clone();
                                        break;
                                    case 10:
                                        to_date = one_ticket.clone();
                                        break;
                                    case 11:
                                        type1_num = one_ticket.clone();
                                        break;
                                    case 12:
                                        type2_num = one_ticket.clone();
                                        break;
                                    case 13:
                                        type3_num = one_ticket.clone();
                                        break;
                                    case 14:
                                        type4_num = one_ticket.clone();
                                        break;
                                }
                                while (k >= 0) {
                                    one_ticket[k] = 0;
                                    k--;
                                }
                                k = 0;
                                j++;
                                continue;
                            }
                            /*读完一条车票信息，加入map中*/
                            if (one_data == ',') {
                                String str_train_number = new String(train_number).trim();
                                String str_from_station = new String(from_station).trim();
                                String str_to_station = new String(to_station).trim();
                                String str_departure_time = new String(departure_time).trim();
                                String str_arrival_time = new String(arrival_time).trim();
                                String str_to_data = new String(to_date).trim();
                                String str_type = new String(train_type);
                                String str_type1_price = new String(type1_price).trim();
                                String str_type2_price = new String(type2_price).trim();
                                String str_type3_price = new String(type3_price).trim();
                                String str_type4_price = new String(type4_price).trim();
                                String str_type1_num = new String(type1_num).trim();
                                String str_type2_num = new String(type2_num).trim();
                                String str_type3_num = new String(type3_num).trim();
                                String str_type4_num = new String(type4_num).trim();

                                /*把数据保存在list2中*/
                                Map<String, String> map = new HashMap<String, String>();

                                map.put("vehicleNum", str_train_number);
                                map.put("startPlace", str_from_station);
                                map.put("endPlace", str_to_station);
                                map.put("startTime", str_departure_time);
                                map.put("endTime", str_arrival_time);
                                map.put("date", str_to_data);
                                map.put("type", str_type.trim());
                                map.put("type1_num", str_type1_num);
                                map.put("type2_num", str_type2_num);
                                map.put("type3_num", str_type3_num);
                                map.put("type4_num", str_type4_num);
                                map.put("show_type1_num", str_type1_num + "张");
                                map.put("show_type2_num", str_type2_num + "张");
                                map.put("show_type3_num", str_type3_num + "张");
                                map.put("type1_price", str_type1_price);
                                map.put("type2_price", str_type2_price);
                                map.put("type3_price", str_type3_price);
                                map.put("type4_price", str_type4_price);
                                map.put("show_type1_price", str_type1_price + "元");
                                map.put("show_type2_price", str_type2_price + "元");
                                map.put("show_type3_price", str_type3_price + "元");

                                if (!str_type4_num.trim().equals("无")) {
                                    map.put("show_type4_num", str_type4_num + "张");
                                    map.put("show_type4_price", str_type4_price + "元");
                                } else {
                                    map.put("show_type4_num", str_type4_num);
                                    map.put("show_type4_price", str_type4_price);
                                }
                                if (str_type.trim().equals("G")){
                                    map.put("type1","二等座:");
                                    map.put("type2","一等座:");
                                    map.put("type3","特等座:");
                                    map.put("type4","无:");
                                }
                                if (str_type.trim().equals("C") ||
                                        str_type.trim().equals("D")){
                                    map.put("type1","无座:");
                                    map.put("type2","二等座:");
                                    map.put("type3","一等座:");
                                    map.put("type4","无:");
                                }
                                if (str_type.trim().equals("T")||
                                        str_type.trim().equals("K") ||
                                        str_type.trim().equals("Z")){
                                    map.put("type1","无座:");
                                    map.put("type2","硬座:");
                                    map.put("type3","硬卧:");
                                    map.put("type4","软卧:");
                                }
                                list2.add(map);

                                Map<String, String> map2 = new HashMap<String, String>();
                                map2.put("date", str_to_data);
                                map2.put("endPlace", str_to_station);
                                map2.put("departure_time", str_departure_time);
                                map2.put("orderNum", str_train_number);
                                map2.put("arrival_time", str_arrival_time);
                                map2.put("startPlace", str_from_station);
                                list.add(map);

                                k = 0;
                                j = 1;
                                continue;
                            }
                            if (one_data == '.') {
                                break;
                            }
                            one_ticket[k] = one_data;
                            k++;
                        }

                        Message m = new Message();
                        m.what=1;
                        myHandler.sendMessage(m);
                    }
                });
                newThread.start();
                try{
                    newThread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }catch (IOException e){

        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_ticket, container, false);
        btn_search = (Button)view.findViewById(R.id.search);
        ibtn_add = (ImageButton)view.findViewById(R.id.imageButton2);
        ibtn_flash = (ImageButton)view.findViewById(R.id.imageButton);
        ibtn_dowmload = (ImageButton)view.findViewById(R.id.imageButton3);

        btn_search.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        v.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape2));
                        break;
                    case MotionEvent.ACTION_UP:
                        v.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape));
                        btn_search.performClick();
                        break;
                }

                return true;
            }
        });

        /*接收车票数据*/
        recv_ticket_msg();
        /*按下载，将12306的车票爬取下来*/
        ibtn_dowmload.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(),activity_dowmload_ticket.class);
                startActivity(i);
            }
        });
        /*按刷新重新接收车票数据*/
        ibtn_flash.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                recv_ticket_msg();
            }
        });
        /*按加号添加车票*/
        ibtn_add.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(), admin_add_ticket.class);
                startActivity(i);
            }
        });
        /*按搜索在map中搜索出符合要求的车票*/
        btn_search.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                EditText train_text = (EditText)getActivity().findViewById(R.id.edt_search_train_num);
                String train_num = train_text.getText().toString();
                if (!train_num.matches("[A-Z]{1}[0-9]{2,4}")) {
                    Message m = new Message();
                    m.what = 2;
                    myHandler.sendMessage(m);

                    return;
                }
                list3.clear();
                for (int i = 0; i < list2.size(); i++) {
                    if (list2.get(i).get("vehicleNum").equals(train_num)){
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("date", list2.get(i).get("date"));
                        map.put("endPlace", list2.get(i).get("endPlace"));
                        map.put("startPlace", list2.get(i).get("startPlace"));
                        map.put("price", list2.get(i).get("price"));
                        map.put("startTime", list2.get(i).get("startTime"));
                        map.put("endTime", list2.get(i).get("endTime"));
                        map.put("vehicleNum", list2.get(i).get("vehicleNum"));
                        map.put("type", list2.get(i).get("type"));
                        map.put("type1", list2.get(i).get("type1"));
                        map.put("type2", list2.get(i).get("type2"));
                        map.put("type3", list2.get(i).get("type3"));
                        map.put("type4", list2.get(i).get("type4"));
                        map.put("type1_num", list2.get(i).get("type1_num"));
                        map.put("type2_num", list2.get(i).get("type2_num"));
                        map.put("type3_num", list2.get(i).get("type3_num"));
                        map.put("type4_num", list2.get(i).get("type4_num"));
                        map.put("type1_price", list2.get(i).get("type1_price"));
                        map.put("type2_price", list2.get(i).get("type2_price"));
                        map.put("type3_price", list2.get(i).get("type3_price"));
                        map.put("type4_price", list2.get(i).get("type4_price"));

                        list3.add(map);
                    }
                }
                ListView lv = (ListView)getActivity().findViewById(R.id.ticket_lv);
                ListAdapter la = new SimpleAdapter(getActivity(), list3,
                        R.layout.activity_show_list_item,
                        new String[]{"type1", "type2", "type3", "type4",
                                "vehicleNum", "startPlace", "endPlace",
                                "startTime", "endTime", "type", "type1_num",
                                "type2_num", "type3_num", "type4_num",
                                "type1_price", "type2_price", "type3_price",
                                "type4_price"},
                        new int[]{R.id.type1, R.id.type2, R.id.type3, R.id.type4, R.id.vehicleNum,
                                R.id.startPlace, R.id.endPlace,
                                R.id.information, R.id.endTime,
                                R.id.type, R.id.num1, R.id.num2,
                                R.id.num3, R.id.num4, R.id.price1,
                                R.id.price2, R.id.price3, R.id.price4});
                lv.setAdapter(la);

            }
        });
        return view;
    }
}